package com.dayu.finecomm.protocol.hd72;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.protocol.codec.Protocol;
import com.dayu.finecomm.protocol.codec.ProtocolDecoder;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.protocol.pojo.TPacket.VType;
import com.dayu.finecomm.protocol.pojo.TSensor;

import io.netty.buffer.ByteBuf;

/**
 * ST协议，详见父类
 * 
 * @author Chenjiawei
 *
 *         2017年6月6日
 */
@Protocol(STDecoder.PROTO)
public class STDecoder extends ProtocolDecoder<TPacket> {

	static final String PROTO = "HD72";

	static Logger LOGGER = LoggerFactory.getLogger(STDecoder.class);

	static int ST_MAGIC_START = 0x53543A; // ST:
	static int ST_MAGIC_END = 0x0D0A; // 回车换行

	static String STR_KV = ";([^:]+):(-?\\d+(\\.\\d*+)?)"; // ;P1:25326380

	static Pattern KV = Pattern.compile(STR_KV);
	static Pattern ST = Pattern.compile(
			"^ST:([0-9]+);" + "(\\d{2,4})[/\\-](\\d{1,2})[/\\-](\\d{1,4}) (\\d{1,2}):(\\d{1,2})(:(\\d{1,2}))?(("
					+ STR_KV + ")+).\r\n$");

	// ST:00553;14/10/29
	// 22:59;P1:25326380;P2:25313712;K5:0;A1:775.1;A2:0.205;H:341.

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dayu.protocol.hd72.ProtocolDecoder#unpack(java.lang.String)
	 */
	@Override
	public TPacket unpack(ByteBuf in) {

		String packet = in.toString(com.dayu.finecomm.utils.Helpers.ASCII);

		Matcher m = ST.matcher(packet);

		if (m.find()) {

			int sn = NumberUtils.toInt(m.group(1));

			// !!! 不要删除 !!!目前时间用的当前时间
			// Calendar cc = Calendar.getInstance();
			//
			// int nYear = NumberUtils.toInt(m.group(2));
			// int nMonth = NumberUtils.toInt(m.group(3));
			// int nDate = NumberUtils.toInt(m.group(4));
			// int nHour = NumberUtils.toInt(m.group(5));
			// int nMinute = NumberUtils.toInt(m.group(6));
			// int nSecond = NumberUtils.toInt(m.group(8), 0);
			//
			// if (nYear < 1000) {
			// nYear += 2000;
			// }
			//
			// // RESOLVE: 11/02/2014 => (nYear, nMonth, nDate) => (nMonth,
			// // nDate,
			// // nYear)
			// if (nDate >= 1000) {
			//
			// // swap(nYear,nDate)
			// int k = nYear;
			// nYear = nDate;
			// nDate = k;
			//
			// // swap(nMonth,nDate)
			// k = nMonth;
			// nMonth = nDate;
			// nDate = k;
			// }
			//
			// cc.set(nYear, nMonth - 1, nDate, nHour, nMinute, nSecond);
			// cc.set(Calendar.MILLISECOND, 0);
			//
			// long timestamp = cc.getTimeInMillis();
			// TPacket s = new TPacket(VType.RRR, PROTO, sn, timestamp);

			TPacket s = new TPacket(VType.RRR, PROTO, sn, System.currentTimeMillis());

			Matcher mm = KV.matcher(m.group(9));

			while (mm.find()) {

				TSensor ts = new TSensor();

				ts.channel = mm.group(1);

				String val = mm.group(2);

				if (val.contains(".")) {
					ts.val = NumberUtils.toFloat(val);
				} else {
					ts.val = NumberUtils.toInt(val);
				}

				s.sensors.add(ts);

			}

			return s;
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dayu.protocol.hd72.ProtocolDecoder#check(io.netty.buffer.ByteBuf)
	 */
	@Override
	public int check(ByteBuf in) {

		if (in.readableBytes() < 8)
			return -1;

		int smagic = in.getUnsignedMedium(0);

		if (smagic != ST_MAGIC_START) {
			return -1;
		}

		int n = in.readableBytes();

		for (int i = in.readerIndex(); i < n; i++) {

			final byte b = in.getByte(i);

			if (b == 0x0D) {
				if (i < n - 1 && in.getByte(i + 1) == 0x0A)
					return i + 2;
			}
		}

		return -1;
	}

	@Override
	public int checkStart(ByteBuf in) {
		return 0;
	}

	@Override
	public Object timing() {
		return HD72Convention.timing();
	}

	@Override
	public byte[] echo() {
		return "@222".getBytes();
	}
}
